package cn.zy.user.service.impl;

import cn.zy.basic.exception.BusinessException;
import cn.zy.basic.jwt.JwtUtils;
import cn.zy.basic.jwt.LoginData;
import cn.zy.basic.jwt.RsaUtils;
import cn.zy.basic.service.impl.BaseServiceImpl;
import cn.zy.basic.service.impl.BaseServiceImpl;
import cn.zy.basic.util.AjaxResult;
import cn.zy.basic.util.HttpUtil;
import cn.zy.basic.util.Md5Utils;
import cn.zy.basic.util.StrUtils;
import cn.zy.sys.domain.Menu;
import cn.zy.user.constant.WxConstants;
import cn.zy.user.domain.Logininfo;
import cn.zy.user.domain.User;
import cn.zy.user.domain.Wxuser;
import cn.zy.user.dto.LoginDto;
import cn.zy.user.mapper.LogininfoMapper;
import cn.zy.user.mapper.UserMapper;
import cn.zy.user.mapper.WxuserMapper;
import cn.zy.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录实现
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.空值校验
        if(StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //2.账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo == null){//根据账号没有查询到信息
            throw new BusinessException("账号错误!!!");
        }
        //3.密码校验
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!inputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误!!!");
        }

        //4.校验是否禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用,请联系管理员!!!");
        }

        //5.将登录信息保存在redis中,30分钟有效,key随机生成
        return loginSuccessJwtHandler(logininfo);
    }


    /**
     *
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求;需要什么code,appid,secret?返回什么?access_token,openid
        //1.准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //2.使用HttpUtil发送微信登录请求:第二个请求,返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastJson将json格式的字符串转成json对象:为了获取token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");//参数名要去平台拷贝
        String openid = jsonObj.getString("openid");
        //4.通过openid查t_wxuser表
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        //4.1查到了-以前扫过码 - 就可以免密登录:返回true,token和logininfo对象
        if(wxuser != null){
            //根据user_id有可能查询到信息
            User user = userMapper.loadById(wxuser.getUserId());
            if(user != null){
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                //免密登录
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);
            }
        }
        //4.2没有查询到 - 第一次扫码 - 把token和openid响应给前端 - 到绑定页面进行绑定
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }


    /**
     * 三方绑定认证实现
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空!!!");
        }
        //2.校验-手机验证码：是否过期，是否正确:[业务键:电话号码 - 手机验证码:时间戳]
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            throw new BusinessException("手机验证码过期!!!");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误!!!");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换Wxuser对象
        Wxuser wxuser =jsonStrWxUser(jsonStr);//user_id=null
        //6.创建User对象和Logininfo对象【phone】 - 难度
        //因为:1.以前通过手机账号注册过,没有绑定微信
        User user = userMapper.loadByPhone(phone);
        if(user==null){
            //手机号码没有绑定过
            user = phone2User(phone);
            Logininfo newLogininfo = user2Logininfo(user);

            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);
        }
        wxuser.setUserId(user.getId()); //微信用户绑定User
        wxuserMapper.save(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(10);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStrWxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }


    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        //传递给前端
        Map<String,Object> map = new HashMap<>();
        //使用jwt加密
        LoginData loginData = new LoginData();
        //1.设置logininfo,前端信息置空,保证安全性
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        //2.设置permissions,menus 判断是否为管理员,如果不是就是用户不走里面的逻辑
        if(logininfo.getType() == 0){
            //设置permissions权限
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置menus菜单
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }

        //3.设置jwtToken 加密 -loginData
        try {
            //通过工具类获取私钥privateKey
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //使用工具类和私钥将loginData加密=>token[jwt token]
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            //将permissions,menus,logininfo,token[jwt token]装到map中响应给前端
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
